package com.example.demo.service;


import com.example.demo.entity.Home;
import com.example.demo.repository.HomeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class HomeService {
    @Autowired
    private HomeRepository homeRepository;  // 注入 HomeRepository

    @Transactional
    public boolean sendToHome(Long id, String name, String type, String num, String phone, String smscontent, String address) {
        try {
            System.out.println("Sending home info: " + id + ", " + name + ", " + type + ", " + num + ", " + phone);
            System.out.println(smscontent);
            Home home = new Home();
            home.setId(id );
            home.setSmsTime(new Date());
            home.setType(type);
            home.setNum(num);
            home.setIsfind(0);
            home.setPhone(phone);
            home.setName(name);
            home.setSmscontent(smscontent);
            home.setAddress(address);
            homeRepository.save(home);
            return true;
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常堆栈信息
            return false;
        }
    }
    public List<Home> getAll() {
        return homeRepository.findAll(); // 获取所有记录
    }
    public boolean isFindStudent(String smsTime, String type, int isfind) {
        try {
            // 将 smsTime 从 String 转换为 Date
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dateSmsTime = format.parse(smsTime);
            // 使用转换后的 Date 进行查询
            Home home = homeRepository.findBySmsTimeAndType(dateSmsTime, type);
            if (home != null) {
                // 找到记录，更新 isfind 字段
                if (isfind == 0) {
                    home.setIsfind(1);
                }else if (isfind == 1) {
                    home.setIsfind(0);
                }
                homeRepository.save(home);  // 保存更新后的记录
                return true;  // 返回更新成功
            } else {
                return false;  // 没有找到记录，返回 false
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;  // 如果发生异常，返回 false
        }
    }
    // 添加事务注解
    @Transactional
    public void deleteisFindStudent(String smsTime, String type) {
        try {
            // 将 smsTime 从 String 转换为 Date
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dateSmsTime = format.parse(smsTime);
            homeRepository.deleteBySmsTimeAndType(dateSmsTime, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

